package com.elvin.zoe.parser.im;

import java.util.ArrayList;
import java.util.List;

import com.elvin.zoe.parser.AbstractParser;
import com.elvin.zoe.pojo.ImMessage;
import com.elvin.zoe.pojo.Message;

public abstract class ImParser extends AbstractParser {

    private int indexCounter = 0;

    @Override
    protected List<Message> parseMessagesFromTokens(List<String> messageTokens) throws Exception {
        List<Message> messages = new ArrayList<Message>();
        for (String messageToken : messageTokens) {
            int type = getMessageType(messageToken);
            String datetimeFormat = getMessageDatetimeFormat();
            String datetime = getMessageDatetime(messageToken);
            String text = getMessageText(messageToken);
            messages.add(new ImMessage(type, datetime, datetimeFormat, text, indexCounter++));
        }
        return refineMessages(messages);
    }

    private List<Message> refineMessages(List<Message> messages) {
        List<Message> refinedMessages = new ArrayList<Message>();
        ImMessage lastMessage = null;
        for (Message message : messages) {
            if (lastMessage == null) {
                lastMessage = (ImMessage) message;
                continue;
            }
            if (lastMessage.merge((ImMessage) message)) {
                continue;
            } else {
                refinedMessages.add(lastMessage);
                lastMessage = (ImMessage) message;
            }
        }
        if (lastMessage != null) {
            refinedMessages.add(lastMessage);
        }
        return refinedMessages;
    }

    protected abstract String getMessageText(String messageToken);

}
